<template>
  <div class="test-question-list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <div class="header">
        <el-row class="search-box">
          <el-col>
            <div class="search-warp">
              <div class="title">课程标题</div>
              <div style="margin-right: 20px;">
                <el-input v-model="searchTitle" placeholder="请输入课程标题" clearable class="search-ipt" @clear="handleSearch" />
              </div>
              <div class="title">姓名</div>
              <div>
                <el-input v-model="searchUsername" placeholder="请输入姓名" clearable class="search-ipt" @clear="handleSearch" />
              </div>
              <div class="button">
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="resetSearchInfo">重置</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card shadow="never" style="border: none;">
      <div class="header-warp">
        <div>
          <el-button text type="primary" icon="el-icon-plus" @click="createCourse">
            创建课程
          </el-button>
          <el-button text icon="el-icon-delete" :disabled="currentItem.length <= 0" @click="batchDeletion">
            批量删除
          </el-button>
        </div>
      </div>
      <div>
        <el-table
          style="width: 100%;"
          :data="course"
          border
          :header-cell-style="{background:'#F5F7FA ',color:'#333333 '}"
          :row-key="getRowKeyOfTarget"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="封面" align="center">
            <template v-slot="{ row }">
              <el-image class="courseAvatar" :src="row.cover">
                <div slot="error">
                  <div class="image-slot">暂无图片</div>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="课程标题" align="center" />
          <el-table-column prop="day" label="完成天数" align="center" />
          <el-table-column label="创建时间" prop="created_at" align="center" />
          <el-table-column label="最后修改时间" prop="updated_at" align="center" />
          <el-table-column align="center" prop="action" label="操作">
            <template v-slot="{ row }">
              <div>
                <span class="action" @click="edit(row)">编辑</span>
                <span class="action" @click="handleCourseInfo(row)">课程详情</span>
              </div>
              <div>
                <span class="action" @click="deleteCourse(row)">删除</span>
                <span class="action" @click="handleStudentInfo(row)">培训人员</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-ination">
        <Pagination
          style="padding-bottom: 0; margin-top: 0;"
          :total="page.total"
          :limit="page.paginate"
          @pagination="pagination"
        />
      </div>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :title="forms ? '创建课程' : '修改课程'"
      width="600px"
      class="test-dialog"
    >
      <el-form ref="formRef" :model="form" :rules="courseRules" label-position="left" label-width="140px">
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入课程标题" />
        </el-form-item>
        <el-form-item label="完成天数" prop="day">
          <el-input v-model="form.day" placeholder="请输入课程完成天数" />
        </el-form-item>
        <el-form-item label="是否为默认课程" prop="day">
          <el-switch
            v-model="form.isDefaultCourse"
          />
        </el-form-item>

        <el-form-item label="课程封面" prop="cover">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="'/api/v1/upload/file'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.cover" :src="form.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="btn-box">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button class="del-button" type="primary" @click="submitTitle('formRef')">
          提 交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
// 修复点: 移除未使用的 addUserCourse 导入，解决 'addUserCourse' is defined but never used 错误
import { course, createCourse, deleteCourses, courseDetail, reviseCourse } from '@/api/train'
import { value } from '@/utils/kris_utils'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      course: [],
      create: [],
      isAddingCourses: false,
      dialogVisible: false,
      forms: null,
      form: {
        title: '',
        cover: '',
        day: '',
        isDefaultCourse: false
      },
      revise: {
        course_id: '',
        title: '',
        cover: '',
        day: '',
        isDefaultCourse: false
      },
      currentItem: [],
      deleteItemInfo: {
        deleteList: [],
        deletionFailureList: [],
        boundIds: [],
        delList: []
      },
      page: {
        paginate: 10,
        page: 1,
        total: 1
      },
      searchTitle: '',
      searchUsername: '',
      addUser: {
        user_id: '',
        course_id: ''
      },
      courseRules: {
        day: [
          { required: true, message: '请输入课程完成天数', trigger: ['blur', 'change'] }
        ],
        title: [
          { required: true, message: '请输入课程标题', trigger: ['blur', 'change'] }
        ],
        cover: [
          { required: true, message: '请输入课程封面', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.showCourse()
  },
  methods: {
    async showCourse() {
      const params = {
        paginate: this.page.paginate,
        page: this.page.page,
        title: this.searchTitle,
        user_name: this.searchUsername,
        user_id: this.$route.query.id ?? undefined
      }
      const res = await course(params)
      console.log(res, 99999)
      this.course = res.data
      this.page.total = res.meta.total
    },
    // 多选
    handleSelectionChange(e) {
      if (this.paperId) {
        this.currentItem = e.map((item, index) => {
          return { ...item, order: index + 1 }
        })
      } else this.currentItem = e.map(item => item.id)
      this.deleteItemInfo.deleteList = e
    },
    async batchDeletion() {
      this.$confirm('是否删除所选中的课程', '提示', { type: 'warning' })
        .then(() => {
          const ids = JSON.stringify(this.currentItem)
          this.deleteItemInfo.delList = this.currentItem
          this.batchDeletionApi(ids)
        })
    },
    async batchDeletionApi(ids) {
      deleteCourses({ course_id: ids })
        .then((res) => {
          this.$message({
            type: 'success',
            message: '删除课程成功'
          })
          this.showCourse()
        })
    },
    createCourse() {
      this.dialogVisible = true
      this.forms = true
      this.form.title = ''
      this.form.cover = ''
      this.form.day = ''
    },
    submitTitle(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid)
        if (!valid) {
          this.$message.error('请输入必填字段')
          return
        }

        if (this.forms) {
          this.dialogVisible = false
          const params = {
            ...this.form,
            'default': this.form.isDefaultCourse ? 1 : null
          }
          createCourse(params)
            .then(() => {
              this.$message({
                message: '创建课程成功',
                type: 'success'
              })
              this.showCourse()
              this.form.title = ''
            })
            .catch(err => {
              console.log(err)
              this.$message.error(value(err, 'response.data.message', '创建课程失败'))
            })
        } else {
          this.dialogVisible = false
          console.log(this.revise)
          this.revise.title = this.form.title
          this.revise.cover = this.form.cover
          this.revise.day = this.form.day
          this.revise['default'] = this.form.isDefaultCourse ? 1 : null

          reviseCourse(this.revise)
            .then(() => {
              this.$message({
                message: '修改课程成功',
                type: 'success'
              })
              this.showCourse()
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    },
    // 修改课程
    edit(row) {
      this.dialogVisible = true
      this.forms = false
      this.form.title = row.title
      this.revise.course_id = row.id
      this.form.cover = row.cover
      this.form.day = row.day
      this.form.isDefaultCourse = row['default'] === 1
    },
    // 删除课程
    deleteCourse(row) {
      const id = JSON.stringify([row.id])
      this.$confirm('是否删除课程', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCourses({ course_id: id })
            .then((res) => {
              this.$message({
                type: 'success',
                message: '删除课程成功'
              })
              this.showCourse()
            })
        })
    },
    handleCourseInfo(row) {
      this.detail(row)
    },
    handleStudentInfo(row) {
      this.learningSituation(row)
    },
    async detail(row) {
      const res = await courseDetail(row.id)
      console.log(res.data, 999)
      this.$router.push({
        path: `/train/detail/${row.id}`
      })
    },
    async learningSituation(row) {
      this.$router.push({
        path: `/train/learningSituation`,
        query: {
          id: row.id,
          tag_title: '学习情况'
        }
      })
    },
    pagination(e) {
      this.page.page = e.page
      this.page.paginate = e.limit
      this.showCourse()
    },
    handleSearch() {
      this.page.page = 1
      this.showCourse()
    },
    resetSearchInfo() {
      this.page = this.$options.data().page
      this.searchTitle = this.$options.data().searchTitle
      this.showCourse()
    },
    handleAvatarSuccess(res) {
      console.log(res, 111)
      this.form.cover = res.data.path
    },
    getRowKeyOfTarget(row) {
      return row.id
    },
    handleCommand(command, row) {
      switch (command) {
        case '1':
          this.detail(row)
          break
        case '2':
          this.learningSituation(row)
          break
      }
    }
  }
}
</script>
<style scoped lang='scss'>
.test-question-list {
  padding: 20px;
  .header{
    display: flex;
    flex-wrap: wrap;
  }
  .header-warp {
    margin: 0 0 20px 0;
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

}

.btn-box {
  margin: 0 0 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-warp {
  margin-top: 20px;
}

.search-box {

  .search-warp {
    display: flex;
    align-items: center;
    width: 100%;

    .title {
      margin-right: 10px;
    }
    .button {
      padding-left: 20px;
    }
  }
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
  width: 178px;
  height: 178px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
.courseAvatar{
  width: 60px;
  height: 60px;
}
.image-slot{
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  background: #F5F7FA;
  color: #C0C4CC;
}
.action{
  padding: 0 10px;
  color:#2F88FF;
  cursor: pointer;
}
</style>
